package com.ayu.wxgzh.ayucyy.service;

import com.alibaba.fastjson.JSONObject;
import com.ayu.wxgzh.ayucyy.entity.TextMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @Author 徐林玉
 * @Description EmojiService
 * @Date 2023/2/28 15:25
 * @Version 1.0
 */
@Service
@Slf4j
public class EmojiService {


    @Value("${crawler.win.path:}")
    private String winPath;


    @Value("${crawler.linux.path:}")
    private String linuxPath;

    private final StringRedisTemplate stringRedisTemplate;

    private final ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    public EmojiService(StringRedisTemplate stringRedisTemplate, ThreadPoolTaskExecutor taskExecutor) {
        this.stringRedisTemplate = stringRedisTemplate;

        this.taskExecutor = taskExecutor;
    }

    public TextMessage getEmojiUrl(Map<String, String> requestMap) throws ExecutionException, InterruptedException {

        //微信服务器在将用户的消息发给公众号的开发者服务器地址（开发者中心处配置）后，微信服务器在五秒内收不到响应会断掉连接，并且重新发起请求，
        //总共重试三次，如果在调试中，发现用户无法收到响应的消息，可以检查是否消息处理超时。关于重试的消息排重，
        //有msgid的消息推荐使用 msgid 排重。事件类型消息推荐使用FromUserName + CreateTime 排重。
        String content = requestMap.get("Content");
        String msgId = requestMap.get("FromUserName");
        String key = msgId + "_url";
        String imgUrl = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(imgUrl) && "1".equals(content)) {
            String reply = "表情处理成功：<a href=\"" + imgUrl + "\">点击下载</a>";
            //清空缓存
            stringRedisTemplate.opsForValue().set(key, "");
            return new TextMessage(requestMap, reply);
        } else {

            if (!content.contains("不支持的消息类型")) {
                return null;
            }
            log.info("winPath:" + winPath);
            log.info("linuxPath:" + linuxPath);
            List<String> lines = new ArrayList<>();
            taskExecutor.execute(() -> {
                String imgUrl2 = "";
                try {
                    //linux要修改路径
//                  final ProcessBuilder processBuilder = new ProcessBuilder("C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\python", winPath);
                    final ProcessBuilder processBuilder = new ProcessBuilder("python", linuxPath);
                    processBuilder.redirectErrorStream(true);
                    final Process process = processBuilder.start();
                    final BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));

                    String line;

                    while ((line = in.readLine()) != null) {
                        lines.add(line);
                    }
                    log.info("python返回：" + JSONObject.toJSONString(lines));
                    //imgUrl = in.readLine();
                    imgUrl2 = lines.get(0);
                    // 缓存路径
                    stringRedisTemplate.opsForValue().set(key, imgUrl2);

                } catch (Exception e) {
                    log.error(e.getMessage());
                }

            });

            String reply = "表情处理中,请10秒后回复1获取";
            return new TextMessage(requestMap, reply);
        }
    }
}
